package com.pt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pt.entity.Checkin;
import com.pt.entity.User;
import com.pt.entity.UserBonusLog;
import com.pt.mapper.CheckinMapper;
import com.pt.service.CheckinService;
import com.pt.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.Random;

@Service
@RequiredArgsConstructor
public class CheckinServiceImpl implements CheckinService {
    
    private final CheckinMapper checkinMapper;
    private final UserService userService;
    
    @Override
    @Transactional
    public Checkin checkin(Long userId) {
        // 检查今日是否已签到
        if (hasCheckedInToday(userId)) {
            throw new RuntimeException("今日已签到");
        }
        
        // 计算奖励魔力值（基础5-15点，连续签到有额外奖励）
        int streak = getCheckinStreak(userId);
        int baseReward = 5 + new Random().nextInt(11); // 5-15点
        int streakBonus = Math.min(streak / 7, 10); // 每连续7天额外1点，最多10点
        int totalReward = baseReward + streakBonus;
        
        // 创建签到记录
        Checkin checkin = new Checkin();
        checkin.setUserId(userId);
        checkin.setCheckinTime(LocalDateTime.now());
        checkin.setRewardPoints(totalReward);
        checkinMapper.insert(checkin);
        
        // 更新用户魔力值
        User user = userService.getUserById(userId);
        user.setBonusPoints(user.getBonusPoints() + totalReward);
        userService.updateUser(user);
        
        // 记录魔力值变更日志
        UserBonusLog log = new UserBonusLog();
        log.setUserId(userId);
        log.setPointsChange(totalReward);
        log.setChangeType(1); // 签到
        log.setDescription("每日签到奖励");
        // 这里需要UserBonusLogService来保存日志
        
        return checkin;
    }
    
    @Override
    public boolean hasCheckedInToday(Long userId) {
        LocalDateTime startOfDay = LocalDate.now().atStartOfDay();
        LocalDateTime endOfDay = LocalDate.now().atTime(LocalTime.MAX);
        
        QueryWrapper<Checkin> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId)
               .between("checkin_time", startOfDay, endOfDay);
        
        return checkinMapper.selectCount(wrapper) > 0;
    }
    
    @Override
    public Integer getCheckinStreak(Long userId) {
        // 获取用户最近的签到记录，计算连续签到天数
        QueryWrapper<Checkin> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId)
               .orderByDesc("checkin_time")
               .last("LIMIT 30"); // 最多查询30天
        
        List<Checkin> checkins = checkinMapper.selectList(wrapper);
        if (checkins.isEmpty()) {
            return 0;
        }
        
        int streak = 0;
        LocalDate currentDate = LocalDate.now();
        
        for (Checkin checkin : checkins) {
            LocalDate checkinDate = checkin.getCheckinTime().toLocalDate();
            
            if (checkinDate.equals(currentDate) || checkinDate.equals(currentDate.minusDays(1))) {
                streak++;
                currentDate = checkinDate.minusDays(1);
            } else {
                break;
            }
        }
        
        return streak;
    }
} 